# obtuse.r
# J. Kirk 23-07-2009
# "Digital Dice" by Paul J. Nahin
# From p. 8
# If a triangle is drawn "at random" inside an arbitrary rectangle, what is the 
# probability the triangle is obtuse?

# This program assumes that you are drawing a 1 x L rectangle, situated at the
# origin.  L is the length of the longer side of the rectangle.
# The final output is an estimate of the probability that the triangle is obtuse.

obtuse <- 0 #total number of obtuse triangles found
length <- 2 #length of the longer side of the rectangle we draw the triangle inside
x<- c()
y<- c()

for (k in 1:1000000)
{

	#generates three random x-coordinates in the range (0,1)
	#generates three random y-coordinates in the range (0,length)
	for (j in 1:3) 
	{
		x[j]<- runif(1)
		y[j]<- length*runif(1)

	}
	
	# Find the square of the length of each side of the triangle using the
	# distance formula
	d1 <- (x[1] - x[2])^2 + (y[4]-y[5])^2
	d2 <- (x[2] - x[3])^2 + (y[5]-y[6])^2
	d3 <- (x[3] - x[1])^2 + (y[6]-y[4])^2

	# Tests to see if the triangle is obtuse or acute
	# The if condition is derived from the cosine formula (see below)
	if (d1 < (d2 +d3) && d2 < (d1 + d3) && d3 < (d1 + d2))
	{
		obtuse = obtuse + 0
	}
	else obtuse = obtuse + 1;
}

print (obtuse/1000000)

## Notes
# The cosine formula:
# For a triangle with sides of length a,b, and c
# the cosine of an angle, say A, is
# cos(A) = (b^2 + c^2 - a^2)/ (2bc)
# Since a positive cosine indicates acute angles, a negative
# cosine indicates obtuse angles, and the denominator must always be positive,
# an angle is acute only if b^2 + c^2 is greater than a^2.  The three parts of the
# if condition check if all three angles in the triangle are acute (as this
# is the only way the triangle could be acute).
